<script>
import Hls from 'hls.js';
import Artplayer from 'artplayer'
import artplayerPluginHlsControl from 'artplayer-plugin-hls-control';
import {proxy} from "@/api/task";

export default {
  name: "VideoView",
  data() {
    return {
      art: '',
      proxy: {
        url: '',
        taskId: '',
        userId: Math.floor(Math.random() * 10000000000000)
      },
      socket: undefined,
      interval: 50000,
      state: 2,
      step: 0,
      steps: [
        '代理服务器连接中...',
        '代理服务器连接成功...',
        '代理服务器代理任务创建中...',
        '代理视频缓存中...',
        '代理视频缓存完成',
        '',
      ],
      process: '123'
    }
  },
  methods: {
    startArt() {
      const artv = new Artplayer({
        container: '.artplayer-app',
        poster: 'https://ss.zlzblog.com:30999/gh4riovd/source/back.png',
        url: '',
        lang: 'zh-cn',
        fullscreen: true,
        pip: true,
        flip: true,
        playbackRate: true,
        aspectRatio: true,
        subtitleOffset: true,
        setting: true,
        controls:[
          {
            name:'进度条',
            html: document.getElementById('processDom'),
            position: 'right',
            tooltip:'服务器缓存进度',
            click: ()=>{
              console.log('1111')
            }
          }
        ],
        plugins: [
          artplayerPluginHlsControl({
            quality: {
              control: true,
              setting: true,
              getName: (level) => level.height + 'P',
              // I18n
              title: '视频质量',
              auto: '自动',
            },
          }),
        ],
        customType: {
          m3u8: function playM3u8(video, url, art) {
            if (Hls.isSupported()) {
              if (art.hls) art.hls.destroy();
              // let retryTimes = 0;
              const hls = new Hls();
              hls.config.fragLoadPolicy.default.errorRetry = {
                maxNumRetry: 0,
                retryDelayMs: 1000,
                maxRetryDelayMs: 15000,
                backoff: 'exponential',
              }
              hls.loadSource(url);
              hls.attachMedia(video);
              hls.on(Hls.Events.MEDIA_ATTACHED, () => {
                art.poster = ''
                hls.on(Hls.Events.ERROR, (event, data) => {
                  if (data.fatal) {
                    switch (data.type) {
                      case Hls.ErrorTypes.NETWORK_ERROR:
                        setTimeout(() => {
                          // if(retryTimes >= 5){
                          //   art.notice.show = '视频缓冲失败请等待或点击刷新按钮重试';
                          // }
                          hls.startLoad()
                          // retryTimes++;
                        }, 1000)
                        break;
                      case Hls.ErrorTypes.MEDIA_ERROR:
                        hls.recoverMediaError();
                        break;
                      default:
                        // cannot recover
                        hls.destroy();
                        break;
                    }
                  }
                });
              });
              art.hls = hls;
              art.on('destroy', () => hls.destroy());
            } else if (video.canPlayType('application/vnd.apple.mpegurl')) {
              video.src = url;
            } else {
              art.notice.show = 'Unsupported playback format: m3u8';
            }
          }
        },
      });
      this.art = artv
    },
    getProxy(play) {
      proxy(this.$route.query.url, this.$route.query.userId).then((res) => {
        this.proxy.url = res.data.url
        this.proxy.taskId = res.data.taskId
        if (play) {
          setTimeout(() => {
            this.step = 1
            setTimeout(() => {
              this.step = 2
              this.art.url = this.proxy.url
              this.startSocket(true)
            }, 800)
          }, 800)
        }
      })
    },
    start() {
      if (this.state === 0) {
        this.startSocket(false)
        this.art.url = this.$route.query.url
        this.state = 1
        return
      }

      if (this.state === 1) {
        this.getProxy(false)
        this.startSocket(true)
        this.state = 2
        return
      }
      if (this.state === 2) {
        this.getProxy(true)
        this.state = 0
      }
    },
    checkState(res) {
      res = JSON.parse(res)
      // 任务等待执行
      if (res.code === 0) {
        this.step = 4
        this.process = 0
        this.step = 3
        return
      }
      // 任务执行中
      if (res.code === 1) {
        this.step = 3
        let min = res.data.minCode - 10000
        let max = res.data.maxCode - 10000
        this.process = (min * 100 / max).toFixed(2) + ''
        return
      }
      // 任务执行完成
      if (res.code === 2) {
        this.socket.close()
        this.process = 0
        if (this.step !== 4) {
          setTimeout(() => {

            this.step = 4
            this.removeCacheInfo()
          }, 1000)
        }
      }

    },
    startSocket(open) {
      if(!open){
        this.socket.close()
        this.removeCacheInfo()
        return
      }
      this.socket = new WebSocket(`ws://localhost:8081/player/websocket/${this.proxy.userId}/${this.proxy.taskId}`);
      console.log(this.socket)
      // Set up event listeners
      this.socket.onopen = () => {
        console.log('WebSocket connection opened.');
      };
      this.socket.onmessage = (event) => {
        this.checkState(event.data)
      };

      this.socket.onerror = (error) => {
        console.error('WebSocket Error:', error);
      };

      this.socket.onclose = () => {
        console.log('WebSocket connection closed.');
      };
    },
    removeCacheInfo() {
      setTimeout(() => {
        this.step = this.steps.length
      }, 1000)
    }
  },
  mounted() {
    this.startArt()
    this.start()
  }

}
</script>

<template>
  <div class="content">
    <div class="desc" :style="`background-color: ${step===4?' none;':'rgba(236, 236, 236, 0.11)'};`">
      <div class="info">
        <span v-if="step < steps.length">{{ steps[step] }}<span v-if="step===3">进度{{ process }}%</span></span>
        <div class="no-proxy" @click="start()">
          <span v-if="state===0">直接播放</span>
          <span v-else-if="state===1">创建代理</span>
          <span v-else>代理播放</span>
        </div>
      </div>
      <div v-if="this.step === 3" :style="`width: ${process}%;`" class="process">

      </div>
    </div>
    <div class="artplayer-app" />
    <div id="processDom">
      <el-progress  type="circle" :percentage="20" :width="22"/>
    </div>
  </div>
</template>

<style scoped>
content, .artplayer-app {
  position: relative;
  height: 100%;
  width: 100%;
}

.desc {
  position: absolute;
  height: 25px;
  width: calc(100% - 10px);
  line-height: 25px;
  font-size: 13px;
  padding: 0 5px;
  color: rgba(151, 197, 234, 0.66);
  z-index: 9999;
  overflow: hidden;
}

.info {
}

.process {
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  z-index: -1;
  background-color: rgba(236, 236, 236, 0.5);
}

.no-proxy {
  text-decoration: underline;
  float: right;
  cursor: pointer;
}
</style>